#####################################################################################
#####			Please cite Georgiadou et al. (2018) as indicated in 			            #####
#####  	https://www.sciencedirect.com/science/article/pii/S026137941830026X		  #####
#####################################################################################


### Note: Set "Replication_Data_Code" as working directory in order to execute code from beginning to end


rm(list = ls(all=T))

#setwd("~/Dropbox/Research/GRR/Far right comparative paper_2000-2012/submission/PublicationDraft/Data/")
setwd("./Data/")

#Load libraries
library(ei)  #R package to implement King's (1997) ecological inference (see https://gking.harvard.edu/eir )
library(foreign)



#### Table 5
#Get data from STATA and create numeric country to use in ecological inference controlling for country effects
farright_ecol<-read.dta(file="ecological_unemployment.dta")
farright_ecol$country2 <- as.numeric(farright_ecol$country)
# use subsample of positive votes for ecological inference
PRR_ecol_nozeros <- farright_ecol[farright_ecol$PRR!=0,]
ER_ecol_nozeros <- farright_ecol[farright_ecol$ER!=0,]

######  Ecological inference on Unemployment
### PRR
formulaPRR_unemp = PRR ~ unemployed
set.seed(123456)
dbufPRR_unemp <- ei(formula=formulaPRR_unemp, total = "validvotes", data=PRR_ecol_nozeros)
set.seed(123456)
dbuf_PRR_unempCov <- ei(formula=formulaPRR_unemp, total = "validvotes", data=PRR_ecol_nozeros, Zb="country2")#Add covariates (country)

### ER
formulaER_unemp = ER ~ unemployed
set.seed(123456)
dbufER_unemp <- ei(formula=formulaER_unemp, total = "validvotes", data=ER_ecol_nozeros)
set.seed(123456)
dbuf_ER_unempCov <- ei(formula=formulaER_unemp, total = "validvotes", data=ER_ecol_nozeros, Zb="country2")#Add covariates (country)

#prepare table of results
sum_unemployment <- cbind(summary(dbufPRR_unemp)[[10]],summary(dbuf_PRR_unempCov)[[10]],summary(dbufER_unemp)[[10]],summary(dbuf_ER_unempCov)[[10]])
sum_unemployment <- round(sum_unemployment,digits = 3)
#setwd("Choose path")

write.csv(sum_unemployment, file="../Tables/ecologicalinference_unemp.csv")




# Figure A4: Scatterplot of FR against Unemployment + regression lines #
#setwd("~/Dropbox/Research/GRR/Far right comparative paper_2000-2012/submission/PublicationDraft/Graphs")
setwd("..")
setwd("./Graphs")

pdf('FigureA4a.pdf',width = 5,height=5.5)
FigureA4a <- plot(dbufPRR_unemp,"xtfitg")
dev.off()
pdf('FigureA4b.pdf',width = 5,height=5.5)
FigureA4b <- plot(dbuf_ER_unempCov,"xtfitg")
dev.off()



setwd("..") ## Return to root directory of paper
